/*
 *  Set.cpp
 *  osnutshell
 *
 *  Created by Zachary  Heylmun on 4/17/10.
 *  Copyright 2010 University of Florida. All rights reserved.
 *
 */

#include "Set.h"

using std::vector;
using std::string;
using std::cout;
using std::ostream;

namespace nutshell
{

	Set::Set() : PROMPT("")
	{
	}
	Set::~Set()
	{
	}


	// BUILT-IN COMMAND FUNCTION FOR set, set path, set prompt
	void Set::do_command(int argc, char** argv)
	{
		if (argc == 1) // just the print function, print full path and current prompt
		{
			cout << "Path = ";
			path();
			cout << "\nPrompt = " << PROMPT << std::endl;
		}
	
		else if (argc < 3 )
			cout << "Illegal Number of Arguments to Set Function.\n";
		else
		{
			string command = argv[1];
			if (command == "path")
			{
				// set path to directories included in arguments
				PATH.clear();
				for (int i = 2; i != argc; ++i)
				{
					set_path( string(argv[i]) );
				}
			}
			else if (command == "prompt")
			{
				// set prompt to string of arguments
				PROMPT.clear();
				for (int i = 2; i != argc; ++i)
				{
					PROMPT += argv[i];
					PROMPT += " ";
				}
			}
			else
				cout << "Invalid Argument for Set Function.\n";
		}
	}




	//path functionality

	// returns a vector of string representing the PATH
	// each string is a directory in the path
	vector<string>& Set::get_path()
	{
		return PATH;
	}

	// prints PATH to stdout
	void Set::path()
	{
		if (PATH.empty())
			return;
		
		vector<string>::const_iterator i = PATH.begin();
		cout << *i++;
		for ( ; i != PATH.end(); ++i)
			cout << " " << *i;
	}

	// adds the directory s to the path
	void Set::set_path(string s)
	{
		PATH.push_back( s );
	}
	//end path functions


	//prompt functionality
	
	// sets the prompt to the string s
	void Set::set_prompt(string s)
	{	
		PROMPT = s;
	}

	// returns the prompt
	// the espace sequence \d will be replaced by the current directory
	string Set::get_prompt()
	{
		string res = PROMPT;
	
		// replace \d with current directory
		int i = res.find("\\d");
		if (i != string::npos)
		{
			res.erase(i, 2);
			char pwd[1024];
		  	if (getcwd(pwd, sizeof(pwd)) != NULL)
			{
				string dir( pwd );
				res.insert(res.begin()+i, dir.begin(), dir.end());
			}
		}
	
		return res;
	}
	
}
